<template>
  <div class="designer-toolbar">
    <!-- 左侧工具栏 -->
    <div class="toolbar-left">
      <!-- 项目信息 -->
      <div class="project-info">
        <i class="el-icon-folder"></i>
        <span class="project-name">{{ projectName }}</span>
        <el-dropdown @command="handleProjectAction" trigger="click">
          <el-button type="text" size="small">
            <i class="el-icon-arrow-down"></i>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="save" icon="el-icon-download">
                保存项目 (Ctrl+S)
              </el-dropdown-item>
              <el-dropdown-item command="save-as" icon="el-icon-folder-add">
                另存为
              </el-dropdown-item>
              <el-dropdown-item command="export" icon="el-icon-upload2">
                导出代码
              </el-dropdown-item>
              <el-dropdown-item command="import" icon="el-icon-upload" divided>
                导入项目
              </el-dropdown-item>
              <el-dropdown-item command="template" icon="el-icon-document">
                保存为模板
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      
      <!-- 项目状态指示器 -->
      <div class="project-status" :class="{ 'has-changes': hasUnsavedChanges }">
        <i :class="hasUnsavedChanges ? 'el-icon-warning' : 'el-icon-success'"></i>
        <span>{{ hasUnsavedChanges ? '有未保存的更改' : '已保存' }}</span>
      </div>
    </div>
    
    <!-- 中间工具栏 -->
    <div class="toolbar-center">
      <!-- 撤销重做 -->
      <el-button-group class="history-controls">
        <el-button
          size="small"
          icon="el-icon-refresh-left"
          :disabled="!canUndo"
          @click="handleUndo"
          title="撤销 (Ctrl+Z)"
        />
        <el-button
          size="small"
          icon="el-icon-refresh-right"
          :disabled="!canRedo"
          @click="handleRedo"
          title="重做 (Ctrl+Y)"
        />
        <el-tooltip content="历史记录" placement="bottom">
          <el-button
            size="small"
            icon="el-icon-time"
            @click="showHistory"
            title="历史记录"
          />
        </el-tooltip>
      </el-button-group>
      
      <!-- 分隔线 -->
      <div class="toolbar-divider"></div>
      
      <!-- 视图控制 -->
      <el-button-group class="view-controls">
        <el-button
          size="small"
          :type="viewMode === 'design' ? 'primary' : ''"
          @click="setViewMode('design')"
          title="设计模式"
        >
          <i class="el-icon-edit"></i>
          设计
        </el-button>
        <el-button
          size="small"
          :type="viewMode === 'preview' ? 'primary' : ''"
          @click="setViewMode('preview')"
          title="预览模式"
        >
          <i class="el-icon-view"></i>
          预览
        </el-button>
        <el-button
          size="small"
          :type="viewMode === 'code' ? 'primary' : ''"
          @click="setViewMode('code')"
          title="代码模式"
        >
          <i class="el-icon-document"></i>
          代码
        </el-button>
      </el-button-group>
      
      <!-- 分隔线 -->
      <div class="toolbar-divider"></div>
      
      <!-- 页面管理 -->
      <div class="page-controls">
        <el-dropdown @command="handlePageAction" trigger="click">
          <el-button size="small">
            <i class="el-icon-document"></i>
            {{ currentPageName }}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="new-page" icon="el-icon-plus">
                新建页面
              </el-dropdown-item>
              <el-dropdown-item command="duplicate-page" icon="el-icon-copy-document">
                复制页面
              </el-dropdown-item>
              <el-dropdown-item command="page-settings" icon="el-icon-setting">
                页面设置
              </el-dropdown-item>
              <el-dropdown-item command="delete-page" icon="el-icon-delete" divided>
                删除页面
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <!-- 页面切换器 -->
        <div class="page-switcher">
          <el-button
            size="small"
            icon="el-icon-arrow-left"
            :disabled="!canGoToPrevPage"
            @click="goToPrevPage"
            title="上一页"
          />
          <span class="page-counter">{{ currentPageIndex + 1 }} / {{ totalPages }}</span>
          <el-button
            size="small"
            icon="el-icon-arrow-right"
            :disabled="!canGoToNextPage"
            @click="goToNextPage"
            title="下一页"
          />
        </div>
      </div>
      
      <!-- 分隔线 -->
      <div class="toolbar-divider"></div>
      
      <!-- 缩放控制 -->
      <div class="zoom-controls">
        <el-button
          size="small"
          icon="el-icon-zoom-out"
          @click="zoomOut"
          title="缩小 (Ctrl+-)"
        />
        <span class="zoom-level">{{ Math.round(zoomLevel * 100) }}%</span>
        <el-button
          size="small"
          icon="el-icon-zoom-in"
          @click="zoomIn"
          title="放大 (Ctrl+=)"
        />
        <el-button
          size="small"
          @click="resetZoom"
          title="重置缩放 (Ctrl+0)"
        >
          100%
        </el-button>
      </div>
    </div>
    
    <!-- 右侧工具栏 -->
    <div class="toolbar-right">
      <!-- 快速操作 -->
      <el-button-group class="quick-actions">
        <el-button
          size="small"
          type="success"
          icon="el-icon-view"
          @click="handlePreview"
          title="预览 (F5)"
        >
          预览
        </el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-download"
          @click="handleSave"
          title="保存 (Ctrl+S)"
        >
          保存
        </el-button>
      </el-button-group>
      
      <!-- 分隔线 -->
      <div class="toolbar-divider"></div>
      
      <!-- 设置 -->
      <el-dropdown @command="handleSettingAction" trigger="click">
        <el-button size="small" icon="el-icon-setting">
          设置
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="preferences" icon="el-icon-setting">
              偏好设置
            </el-dropdown-item>
            <el-dropdown-item command="shortcuts" icon="el-icon-keyboard">
              快捷键
            </el-dropdown-item>
            <el-dropdown-item command="themes" icon="el-icon-brush">
              主题
            </el-dropdown-item>
            <el-dropdown-item command="plugins" icon="el-icon-connection">
              插件管理
            </el-dropdown-item>
            <el-dropdown-item command="about" icon="el-icon-info" divided>
              关于
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      
      <!-- 分隔线 -->
      <div class="toolbar-divider"></div>
      
      <!-- 帮助 -->
      <el-button
        size="small"
        icon="el-icon-question"
        @click="showHelp"
        title="帮助 (F1)"
      />
      
      <!-- 用户信息 -->
      <el-dropdown @command="handleUserAction" trigger="click">
        <div class="user-avatar">
          <i class="el-icon-user"></i>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile" icon="el-icon-user">
              个人资料
            </el-dropdown-item>
            <el-dropdown-item command="settings" icon="el-icon-setting">
              账户设置
            </el-dropdown-item>
            <el-dropdown-item command="logout" icon="el-icon-switch-button" divided>
              退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    
    <!-- 历史记录弹窗 -->
    <el-dialog
      v-model="historyVisible"
      title="操作历史"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="history-content">
        <div class="history-list">
          <div
            v-for="(record, index) in historyRecords"
            :key="index"
            class="history-item"
            :class="{ active: index === currentHistoryIndex }"
            @click="goToHistory(index)"
          >
            <div class="history-icon">
              <i :class="getHistoryIcon(record.type)"></i>
            </div>
            <div class="history-info">
              <div class="history-title">{{ record.title }}</div>
              <div class="history-time">{{ formatTime(record.timestamp) }}</div>
            </div>
            <div class="history-action">
              <el-button
                size="small"
                type="primary"
                @click.stop="goToHistory(index)"
              >
                恢复
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="historyVisible = false">关闭</el-button>
        <el-button type="primary" @click="clearHistory">清空历史</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'

// Props
const props = defineProps({
  canUndo: {
    type: Boolean,
    default: false
  },
  canRedo: {
    type: Boolean,
    default: false
  },
  projectName: {
    type: String,
    default: '未命名项目'
  },
  currentPageName: {
    type: String,
    default: '页面1'
  },
  currentPageIndex: {
    type: Number,
    default: 0
  },
  totalPages: {
    type: Number,
    default: 1
  },
  hasUnsavedChanges: {
    type: Boolean,
    default: false
  },
  zoomLevel: {
    type: Number,
    default: 1
  }
})

// Emits
const emit = defineEmits([
  'undo',
  'redo',
  'save',
  'preview',
  'view-mode-change',
  'page-action',
  'setting-action',
  'user-action',
  'zoom-change',
  'page-change',
  'history-action'
])

// 响应式状态
const viewMode = ref('design')
const historyVisible = ref(false)
const historyRecords = ref([])
const currentHistoryIndex = ref(-1)

// 计算属性
const canGoToPrevPage = computed(() => props.currentPageIndex > 0)
const canGoToNextPage = computed(() => props.currentPageIndex < props.totalPages - 1)

// 方法
const handleUndo = () => {
  emit('undo')
}

const handleRedo = () => {
  emit('redo')
}

const setViewMode = (mode) => {
  viewMode.value = mode
  emit('view-mode-change', mode)
}

const handleProjectAction = (command) => {
  switch (command) {
    case 'save':
      emit('save')
      break
    case 'save-as':
      emit('project-action', 'save-as')
      break
    case 'export':
      emit('project-action', 'export')
      break
    case 'import':
      emit('project-action', 'import')
      break
    case 'template':
      emit('project-action', 'template')
      break
  }
}

const handlePageAction = (command) => {
  emit('page-action', command)
}

const handleSettingAction = (command) => {
  emit('setting-action', command)
}

const handleUserAction = (command) => {
  emit('user-action', command)
}

const handleSave = () => {
  emit('save')
}

const handlePreview = () => {
  emit('preview')
}

const goToPrevPage = () => {
  if (canGoToPrevPage.value) {
    emit('page-change', props.currentPageIndex - 1)
  }
}

const goToNextPage = () => {
  if (canGoToNextPage.value) {
    emit('page-change', props.currentPageIndex + 1)
  }
}

const zoomIn = () => {
  const newZoom = Math.min(props.zoomLevel * 1.2, 3)
  emit('zoom-change', newZoom)
}

const zoomOut = () => {
  const newZoom = Math.max(props.zoomLevel / 1.2, 0.1)
  emit('zoom-change', newZoom)
}

const resetZoom = () => {
  emit('zoom-change', 1)
}

const showHistory = () => {
  historyVisible.value = true
  // 这里应该从store获取历史记录
  loadHistoryRecords()
}

const loadHistoryRecords = () => {
  // 模拟历史记录数据
  historyRecords.value = [
    {
      type: 'add',
      title: '添加按钮组件',
      timestamp: Date.now() - 1000 * 60 * 5
    },
    {
      type: 'edit',
      title: '修改文本内容',
      timestamp: Date.now() - 1000 * 60 * 10
    },
    {
      type: 'delete',
      title: '删除图片组件',
      timestamp: Date.now() - 1000 * 60 * 15
    }
  ]
}

const goToHistory = (index) => {
  currentHistoryIndex.value = index
  emit('history-action', { action: 'go-to', index })
}

const clearHistory = () => {
  historyRecords.value = []
  emit('history-action', { action: 'clear' })
  historyVisible.value = false
}

const getHistoryIcon = (type) => {
  const icons = {
    add: 'el-icon-plus',
    edit: 'el-icon-edit',
    delete: 'el-icon-delete',
    move: 'el-icon-rank',
    style: 'el-icon-brush'
  }
  return icons[type] || 'el-icon-info'
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 1000 * 60) {
    return '刚刚'
  } else if (diff < 1000 * 60 * 60) {
    return `${Math.floor(diff / (1000 * 60))}分钟前`
  } else if (diff < 1000 * 60 * 60 * 24) {
    return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

const showHelp = () => {
  // 显示帮助信息
  console.log('显示帮助信息')
}

// 键盘快捷键
const handleKeydown = (event) => {
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 'z':
        if (!event.shiftKey) {
          event.preventDefault()
          handleUndo()
        }
        break
      case 'y':
        event.preventDefault()
        handleRedo()
        break
      case 's':
        event.preventDefault()
        handleSave()
        break
      case '=':
      case '+':
        event.preventDefault()
        zoomIn()
        break
      case '-':
        event.preventDefault()
        zoomOut()
        break
      case '0':
        event.preventDefault()
        resetZoom()
        break
    }
  } else if (event.key === 'F1') {
    event.preventDefault()
    showHelp()
  } else if (event.key === 'F5') {
    event.preventDefault()
    handlePreview()
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.designer-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  gap: 16px;
  min-height: 56px;
}

.toolbar-left,
.toolbar-center,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toolbar-center {
  flex: 1;
  justify-content: center;
}

.project-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.project-info i {
  color: #409eff;
  font-size: 16px;
}

.project-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.project-status {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.project-status.has-changes {
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.project-status:not(.has-changes) {
  background: #f0f9ff;
  color: #67c23a;
  border: 1px solid #b3d8ff;
}

.toolbar-divider {
  width: 1px;
  height: 20px;
  background: #e4e7ed;
  margin: 0 4px;
}

.history-controls,
.view-controls,
.page-controls,
.zoom-controls,
.quick-actions {
  display: flex;
  align-items: center;
  gap: 1px;
}

.page-controls {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-switcher {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #606266;
}

.page-counter {
  padding: 0 8px;
  font-weight: 500;
}

.zoom-controls {
  display: flex;
  align-items: center;
  gap: 4px;
}

.zoom-level {
  padding: 0 8px;
  font-size: 12px;
  color: #606266;
  min-width: 40px;
  text-align: center;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f0f9ff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e4e7ed;
}

.user-avatar:hover {
  background: #e6f7ff;
  transform: scale(1.05);
}

.user-avatar i {
  color: #409eff;
  font-size: 16px;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 4px;
}

.el-button-group .el-button {
  border-radius: 0;
}

.el-button-group .el-button:first-child {
  border-radius: 4px 0 0 4px;
}

.el-button-group .el-button:last-child {
  border-radius: 0 4px 4px 0;
}

/* 历史记录弹窗样式 */
.history-content {
  max-height: 400px;
  overflow-y: auto;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.history-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.history-item.active {
  border-color: #409eff;
  background: #e6f7ff;
}

.history-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.history-icon i {
  font-size: 16px;
  color: #409eff;
}

.history-info {
  flex: 1;
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.history-action {
  opacity: 0;
  transition: opacity 0.2s ease;
}

.history-item:hover .history-action {
  opacity: 1;
}

/* 响应式设计 - 保持水平布局 */
@media (max-width: 1200px) {
  .designer-toolbar {
    flex-direction: row; /* 保持水平布局 */
    gap: 16px; /* 保持原有间距 */
    padding: 12px 16px;
  }
  
  .toolbar-left,
  .toolbar-center,
  .toolbar-right {
    justify-content: flex-start; /* 保持左对齐 */
    width: auto; /* 保持自动宽度 */
  }
  
  /* 移除重新排序，保持原有顺序 */
  .toolbar-center {
    order: unset;
  }
  
  .toolbar-left {
    order: unset;
  }
  
  .toolbar-right {
    order: unset;
  }
}

@media (max-width: 768px) {
  .project-name {
    max-width: 150px;
  }
  
  .toolbar-center {
    flex-wrap: wrap;
    gap: 4px;
  }
  
  .page-controls,
  .zoom-controls {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
